import json
import random
from init_db import conn
import numpy as np
from datetime import datetime, timedelta
from decimal import Decimal

# 随机定义频道id
channel_id = [1, 2, 3, 4, 5, 6]


def generate_random_time(start_time, end_time):
    start_timestamp = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S").timestamp()
    end_timestamp = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S").timestamp()
    random_timestamp = random.uniform(start_timestamp, end_timestamp)
    random_time = datetime.fromtimestamp(random_timestamp).strftime("%Y-%m-%d %H:%M:%S")
    return random_time


def query_items_id(sql):
    try:
        with conn.cursor() as cursor:
            cursor.execute(sql)
        # 这种转换只是包了一层list，实际里面每个元素还是元祖
        # result = list(cursor.fetchall())
        results = cursor.fetchall()
        # 处理每个元组，去除Decimal部分
        processed_rows = []
        for row in results:
            for value in row:
                if isinstance(value, Decimal):
                    processed_rows.append(str(value))  # 将Decimal转换为字符串
                else:
                    processed_rows.append(value)
        return processed_rows
    except Exception as e:
        print(f"Error: {e}")
        return None


sql = "select user_id from user_basic limit 100000"
sql2 = "select article_id from news_article_basic limit 100000"

user_ids = list(query_items_id(sql))
article_ids = list(query_items_id(sql2))
data = []


def generate_data(rows, file):
    for i in range(rows):
        json_obj = {
            "actionTime": generate_random_time(start_time="2022-01-01 00:00:00",
                                               end_time="2022-01-01 23:59:59"),
            "readTime": str(random.randint(10, 1000)),
            "channelId": random.randint(1, 50),
            "param": {
                "action": "read",
                "userId": random.choice(user_ids),
                "articleId": random.choice(article_ids),
                "algorithmCombine": "C2",
            }
        }
        # indent参数来指定缩进量, sort_keys参数来指定是否要对字典的键进行排序,这里很明显需要按照我写法的指定格式返回,使用字符串切片操作[1:-1]去除首尾的方括号
        json_text = json.dumps(json_obj, sort_keys=False) + '\n'
        file.write(json_text)


if __name__ == '__main__':
    with open('../dataset/user_click.log', 'w') as file:
        generate_data(5, file)
